﻿using Adp.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Yqd.Core;
using System.Linq;
using Newtonsoft.Json.Linq;
using Yqd.Enm;

namespace Yqd.Controllers.Filter
{
    public class UserAttribute : ActionFilterAttribute
    {
        private bool IsValid;
        public UserAttribute(bool IsValid = true)
        {
            this.IsValid = IsValid;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            var wx = WxUser.LogonInfo;
            if (wx == null)
            {
                context.Result = new JsonResult(new
                {
                    nologin = true,
                    message = "登录超时，请重新授权登录！"
                });
                return;
            }
            var platform = Form.GetInt("platform", 0);
            if (IsValid && !WxUser.Platform.Any(it => it.Value == platform) && !wx.Role.Any(it => it > 角色类型.未设置 && it < 角色类型.协调人))
            {
                context.Result = new JsonResult(new
                {
                    nopermit = true,
                    message = "您暂无权限访问，请与管理员联系！"
                });
                return;
            }
        }
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
            var wx = WxUser.LogonInfo;
            var jr = (JsonResult)context.Result;
            if (jr != null)
            {
                var r = JObject.FromObject(jr.Value);
                r["Authorization"] = JObject.FromObject(new
                {
                    AllowOperate = wx.Permit.Any(it => it == Enm.权限清单.允许操作),
                    IsAdmin = wx.Role.Any(it => it == Enm.角色类型.管理员)
                });
                context.Result = new JsonResult(r);
            }
        }
    }
}